import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ErrorCode } from '../../../common/constants/error-code.enum';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  /**
   * 处理认证失败的情况
   * @param err 错误信息
   * @returns 抛出未授权异常
   */
  handleRequest(err: any, user: any) {
    if (err || !user) {
      throw new UnauthorizedException({
        code: ErrorCode.UNAUTHORIZED,
        message: '未授权访问',
      });
    }
    // eslint-disable-next-line @typescript-eslint/no-unsafe-return
    return user;
  }
}
